package app.msy.cn.takephoto.util;

import android.graphics.Bitmap;
import android.os.Environment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {

    private static final String TEMP_DIR = Environment.getExternalStorageDirectory().getPath() + "/takePhoto/temp/";

    private static final String IMG_DIR = Environment.getExternalStorageDirectory().getPath() + "/takePhoto/photo/";

    /**
     * 功能描述：检测SD卡是否存在
     */
    public static boolean isSDCardExist() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 功能描述：获取/新建临时目录
     */
    public static String getTempDir() {
        File file = new File(TEMP_DIR);
        if (!file.exists()) {
            boolean result = file.mkdirs();
        }
        return TEMP_DIR;
    }

    /**
     * 功能描述：获取/新建存储图片目录
     */
    public static String getImageDir() {
        File file = new File(IMG_DIR);
        if (!file.exists()) {
            boolean result = file.mkdirs();
        }
        return IMG_DIR;
    }

    /**
     * 功能描述：保存bitmap对象至本地
     */
    public static String saveBitmap(Bitmap bitmap, String filePath) {
        File file = new File(filePath);
        BufferedOutputStream bos = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
                bos = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.flush();
                bos.close();
                bitmap.recycle();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }
}
